<template>
  <el-dropdown @command="onAction">
    <os-icon name="user" size="18" class="m-r-5 cp"/>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item command="pwd">修改密码</el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  name: 'UserIcon',
  data () {
    return {
      rule: [
        { type: 'Input', title: '原密码', field: 'oldpassword', props: { type: 'password' }, validate: [this.$v.required()] },
        { type: 'Input', title: '新密码', field: 'password', props: { type: 'password' }, validate: [this.$v.required()] },
        { type: 'Input', title: '确认新密码', field: 'confirmpassword', props: { type: 'password' }, validate: [this.$v.required(), this.$v.validator(this.validatorPWD)] }
      ],
      option: {
        ...this.$utils.formOptions(160, 24)
      },
      fApi: null
    }
  },
  computed: {
    ...mapGetters('system', ['userInfo'])
  },
  methods: {
    validatorPWD (rule, value, callback) {
      const user = this.fApi.formData()
      if (user.password !== user.confirmpassword) {
        callback(new Error('2次输入密码不一致'))
      } else {
        callback()
      }
    },
    onAction (action) {
      if (action === 'pwd') {
        this.changePwd()
      }
    },
    changePwd () {
      const btn = [{ text: '保存', loading: true, cb: this.save }]
      this.$utils.dialog('修改密码', <form-create vModel={this.fApi} rule={this.rule} option={this.option}></form-create>, { btn, width: '60%' })
    },
    save (cb) {
      this.fApi.validate(async v => {
        if (v) {
          const params = {
            username: this.userInfo.userName,
            ...this.fApi.formData()
          }
          const { error } = await this.$store.dispatch('system/changePwd', params)
          cb()
          if (error) {
            this.$utils.message.error(error.message)
          } else {
            this.$utils.message.success('修改成功')
            this.$utils.hideDialog()
          }
        } else {
          cb()
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
